<template>
  <div class="insert-form-box flex-col-start">
    <div class="insert-form" v-loading="loading">
      <el-form ref="form"   :model="form" :rules="rules" label-width="120px"  status-icon  >
        <el-form-item  label="公寓名" prop="apartmentName">
          <el-input v-model="form.apartmentName" placeholder="请输入公寓名" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input  style="width: 400px" v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="详细描述" prop="description">
          <el-input type="textarea" :rows="6" style="width: 400px" v-model="form.description" placeholder="请输入详细描述" />
        </el-form-item>
        <el-form-item label="开启状态" prop="isDelete">
          <template slot-scope="">
            <el-switch active-text="开启"
                       inactive-value="关闭"
                       :active-value="0" :inactive-value="1"
                       v-model="form.isDelete" ></el-switch>
          </template>
        </el-form-item>


        <el-form-item label="公寓设施" prop="stuff" >
          <el-checkbox-group v-model="form.stuffList" @change="handleStuffChange">
            <el-checkbox v-for="stuff in stuffOptions" :label="stuff.id" :key="stuff.id">{{stuff.stuffName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="费用类型" prop="feetype" >
          <el-checkbox-group v-model="form.feetypeList" @change="handleFeetypeChange">
            <el-checkbox v-for="feetype in feetypeOptions" :label="feetype.id" :key="feetype.id">{{feetype.feetype}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>


        <el-form-item label="安全保障" prop="security" >
          <el-select size="medium"  collapse-tags v-model="form.securityList" multiple placeholder="请选择安全保障">
            <el-option
                v-for="item in securityOptions"
                :key="item.id"
                :label="item.securityName"
                :value="item.id">
            </el-option>
          </el-select>

        </el-form-item>


        <el-form-item label="禁止事项" prop="forbid" >

          <el-checkbox-group v-model="form.forbidList" @change="handleForbidChange">
            <el-checkbox v-for="item in forbidOptions"  :label="item.id" :key="item.id">{{item.forbidName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="取消策略" prop="cancel">
          <el-radio-group v-model="form.cancel">
            <el-radio :label="cancel.id" v-for="cancel in cancelOptions">{{cancel.cancelName}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="临近学校" prop="school"  >
          <el-table
              ref="schoolTable"
              :data="form.schoolList"
              style="width: 100%">
            <el-table-column
                type="selection"
                width="55">
            </el-table-column>
            <el-table-column type="expand" width="100px"  >

              <template slot-scope="scope">

                <div class="flex-col">
                  <div>
                    <div>学校名称</div>
                    <el-autocomplete
                        v-model="scope.row.schoolName"
                        :fetch-suggestions="querySearchSchoolAsync"
                        placeholder="请输入内容"
                        @select="handleSelect(scope.$index,$event)"
                    ></el-autocomplete>
                  </div>
                  <div>
                    <span>步行时间</span>
                    <el-input v-model="scope.row.onfoot" ></el-input>
                  </div>
                  <div>
                    <span>公交车时间</span>
                    <el-input v-model="scope.row.bybus" ></el-input>
                  </div>
                  <div>
                    <span>出租车时间</span>
                    <el-input v-model="scope.row.bytexi" ></el-input>
                  </div>
                  <el-button type="primary" style="margin-top: 20px" @click="handleClickToggleRow(scope.row,false)" size="mini">确定</el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column
                width="100"
                label="学校名称"
                prop="schoolName">
            </el-table-column>
            <el-table-column
                width="100"
                label="步行"
            >
              <template slot-scope="scope">
                {{scope.row.onfoot}}分钟
              </template>
            </el-table-column>

            <el-table-column
                width="100"
                label="公交车"
                >
              <template slot-scope="scope">
                {{scope.row.bybus}}分钟
              </template>
            </el-table-column>

            <el-table-column
                width="100"
                label="出租车"
                >
              <template slot-scope="scope">
                {{scope.row.bytexi}}分钟
              </template>
            </el-table-column>
            <el-table-column
                width="100"
                label="操作"
            ><template slot-scope="scope">
              <el-button type="danger" icon="el-icon-delete" circle size="mini" @click="handleRemoveSchool(scope.row,scope.$index)"></el-button>
            </template>

            </el-table-column>
          </el-table>

          <el-button type="text" @click="handleClickAddSchool"  style="margin-top: 20px">+ 添加学校</el-button>
        </el-form-item>

        <el-form-item label="城市" >
          <el-select
              v-model="form.cityList"
              multiple
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词"
              collapse-tags
              value-key="id"
              no-match-text="没有找到该城市"
              :remote-method="remoteSearchCity"
              :loading="cityLoading">
            <el-option

                v-for="(item,index) in suggestionCityList"
                :key="item.id"
                :label="item.cityName"
                :value="item">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="上传公寓照片" prop="image" >
          <FileUpload :on-remove="handleRemoveImage" :file-list="form.imageList"  @success="handleUploadSuccess"></FileUpload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {listStuff} from "@/api/stuff/stuff";
import {listFeetype} from "@/api/feetype/feetype";
import {listForbid} from "@/api/forbid/forbid";
import {listSecurity} from "@/api/security/security";
import {listCancel} from "@/api/cancel/cancel";
import FileUpload from "@/components/upload/FileUpload.vue";
import apartmentApi from "@/api/apartment/apartment";
import TransButton from "@/components/button/TransButton.vue";
import {getSchoolByKeyword} from "@/api/school/school";
import {searchCityListByKeyword} from "@/api/city/city";

export default {
  name: "InsertApartmentForm",
  components: {TransButton, FileUpload},
  data() {
    return {
      cityLoading:false,
      loading:false,
      method:0,
      form:{
        cityList:[],
        apartmentName:"",
        address:"",
        description:"",
        isDelete:0,
        stuffList:[],
        feetypeList:[],
        securityList:[],
        cancel:1,
        forbidList:[],
        schoolList:[],
        imageList:[]
      },
      rules:{},
      stuffOptions:[],
      feetypeOptions:[],
      securityOptions:[],
      forbidOptions:[],
      cancelOptions:false,
      query:{
        isDelete: 0,
        pageNum:1,
        pageSize:100
      },
      suggestionCityList:[]
    }
  },
  methods: {
    querySearchSchoolAsync(queryString, cb){

      getSchoolByKeyword(queryString).then(resp=>{

          let list= resp.data.map(i=>{
            return{
              value:i.schoolName,
              school:i
            }
          })
          cb(list)

      })
    },
    // 学校搜索
    handleSelect(index,val){
      this.form.schoolList[index].schoolId=val.school.id
      console.log(this.form.schoolList)
    },

    getVo(form){
      let apartmentVo={
        ...this.form
      }
      apartmentVo.stuffList=this.mapToIdObjList(this.form.stuffList)
      apartmentVo.forbidList=this.mapToIdObjList(this.form.forbidList)
      apartmentVo.securityList=this.mapToIdObjList(this.form.securityList)
      apartmentVo.feetypeList=this.mapToIdObjList(this.form.feetypeList)
      apartmentVo.cancel={id:this.form.cancel}
      apartmentVo.imageList=this.form.imageList.map(item=>item.url)

      apartmentVo.schoolList=this.form.schoolList.filter((i)=>{
        return i.schoolId === 0
      })
      return apartmentVo
    },

    insert(){
      let apartmentVo=this.getVo(this.form)


      this.loading=true
      apartmentApi.addApartment(apartmentVo).then(resp=>{
        if(resp.code === 200){
          this.$message.success("添加成功")
          this.$router.push("/bg/apartment")
        }else{
          this.$message.error("添加失败:"+resp.msg)
        }
        this.loading=false
      })
    },
    update(){
      let apartmentVo=this.getVo(this.form)
      this.loading=true
      apartmentApi.updateApartment(apartmentVo).then(resp=>{
            if(resp.code === 200){
                  this.$message.success("添加成功")
                  this.$router.push("/bg/apartment")
            }else{
              this.$message.error("添加失败:"+resp.msg)
            }
            this.loading=false
      })
    },
    submitForm(){
      let validate = this.$refs.form.validate().then(res=>{
        if(this.method === 0){
          this.insert()
        }else{
          this.update()
        }
      })


    },
    cancel(){
      this.$router.push("/bg/apartment")
    },
    handleUploadSuccess(resp){
      let response=resp.response
      if(response.code === 200){
        this.form.imageList.push({
          uuid:new Date().getTime(),
          name:`图${this.form.imageList.length+1}`,
          url:response.data
        })
      }
    },
    handleStuffChange(val){
      this.form.stuffList=val
    },
    handleFeetypeChange(val){
      this.form.feetypeList=val
    },
    handleSecurityChange(val){

    },
    handleForbidChange(val){
      this.form.forbidList=val
    },

    getStuffOptions(){
      listStuff(this.query).then(resp=>{
        if(resp.code === 200){
          this.stuffOptions=resp.data.list
        }
      })
    },
    getFeetypeOptions(){
      listFeetype(this.query).then(resp=>{
        if(resp.code === 200){
          this.feetypeOptions=resp.data.list
        }
      })
    },
    getForbidOptions(){
      listForbid(this.query).then(resp=>{
        if(resp.code === 200){
          this.forbidOptions=resp.data.list
        }
      })
    },
    getSecurityOptions(){
      listSecurity(this.query).then(resp=>{
        if(resp.code === 200){
          this.securityOptions=resp.data.list
        }
      })
    },
    getCancelOptions(){
      listCancel(this.query).then(resp=>{
        if(resp.code === 200){
          this.cancelOptions=resp.data.list
        }
      })
    },
    mapToIdObjList(list){
      return list.map((item)=>{
        return {
          id:item
        }
      })
    },
    mapToIdList(list){
      return list.map((item)=>{
        return item.id
      })
    },
    getApartmentDetailInfo(aId){
      this.loading=true
      apartmentApi.getDetailById(aId).then(resp=>{
        if(resp.code === 200){
          let data=resp.data
          this.form.apartmentName=data.apartmentName
          this.form.description=data.description
          this.form.address=data.address

          this.form.feetypeList=this.mapToIdList(data.feetypeList)


          this.form.forbidList=this.mapToIdList(data.forbidList)

          this.form.securityList=this.mapToIdList(data.securityList)

          this.form.stuffList=this.mapToIdList(data.stuffList)

          this.form.cancel=resp.data.cancel.id

          // 暂无图片
          this.form.imageList=resp.data.imageList.map((image,index)=>{
            return {
              uid:new Date().getTime()+index,
              name:`图${index+1}`,
              url:image
            }
          })

          this.loading=false
        }
      })
    },
    /**
     * file :{
     *
     *   name,
     *   uid,
     *   url,
     *   status
     * }
     *
     * */

    handleRemoveImage(file){

      if(file.status === 'success'){
        this.form.imageList=this.form.imageList.filter((image)=>{
          return image.uid===file.uid
        })
      }

    },
    // 删除学校
    handleRemoveSchool(row,index){
      this.$confirm("确定删除吗?").then(()=>{

        this.form.schoolList.splice(index,1)
      })
    },
    /**
     *  收起/展开学校详情
     *
     * */
    handleClickToggleRow(row,bool){
      this.$refs.schoolTable.toggleRowExpansion(row,bool)
    },
    // 添加一个学校栏到表格里
    handleClickAddSchool(){


      let arr=this.form.schoolList
      let len=arr.length
      let obj={
        schoolId:0,
        schoolName: "",
        onfoot:0,
        bybus:0,
        bytexi:0
      }
      if(len === 0){
        arr.push(obj)
        return
      }
      if(arr[len-1].id !==0 ){
        arr.push(obj)
        // this.$refs.schoolTable.toggleRowExpansion(obj,true)
      }else{
        this.$message.warning("请先输入上一个")
      }


    },

    remoteSearchCity(val){
      searchCityListByKeyword(val).then(resp=>{

        this.suggestionCityList=resp.data
      })
    },
    init(){
      let aId = this.$route.query.aId;
      if(aId){
        // 1 编辑 需要填充数据 / 0 新增
        this.method=1
        this.getApartmentDetailInfo(aId)
      }else{
        this.method=0

      }
    }
  },
  mounted() {
    this.getStuffOptions()
    this.getFeetypeOptions()
    this.getForbidOptions()
    this.getSecurityOptions()
    this.getCancelOptions()
    this.init()
  }
}
</script>

<style scoped lang="less">
  .insert-form-box{
      padding: 30px 0;
      .insert-form{
        width: 70%;
        padding-bottom: 100px;
        .el-form-item{
          width: 100%;
          display: flex;
          justify-content: flex-start;
          align-items: flex-start;
          flex-wrap: wrap;
        }
      }
  }
</style>